package com.shey.imageloader.bean;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.shey.imageloader.impl.IBitmapCache;
import com.shey.utils.BitmapDecoder;

/**
 * Created by SheyChen on 2015/12/2 17:03.
 * Email 1768037936@qq.com
 */
public class DoubleCache implements IBitmapCache {

    private static final String TAG = "DoubleCache";
    private DiskCache mDiskCache;
    private MemoryCache mMemoryCache = new MemoryCache();

    public DoubleCache(Context context) {
        mDiskCache = DiskCache.getDiskCache(context);
    }

    @Override
    public Bitmap get(final BitmapRequest bitmapRequest) {

        if (bitmapRequest == null) return null;

        Bitmap bitmap = mMemoryCache.get(bitmapRequest);
        if (bitmap == null) {
            bitmap = mDiskCache.get(bitmapRequest);
            /**
             * 内存和磁盘缓存都为空的时候
             */
            if (bitmap == null) {
                BitmapDecoder bitmapDecoder = new BitmapDecoder() {
                    @Override
                    public Bitmap decodeBitmapWithOption(BitmapFactory.Options options) {
                        Bitmap bitmap = BitmapFactory.decodeFile(bitmapRequest.imageUri, options);
                        return bitmap;
                    }
                };
                bitmap = bitmapDecoder.decodeBitmap(200, 200);
                put(bitmapRequest, bitmap);
            } else {
                mMemoryCache.put(bitmapRequest,bitmap);
            }
        }

        return bitmap;
    }

    @Override
    public synchronized void put(BitmapRequest bitmapRequest, Bitmap bitmap) {
        if (bitmapRequest != null && bitmap != null) {
            mMemoryCache.put(bitmapRequest,bitmap);
            mDiskCache.put(bitmapRequest,bitmap);
        }
    }

    @Override
    public void remove(BitmapRequest bitmapRequest) {
        if (bitmapRequest == null) return;

        mMemoryCache.remove(bitmapRequest);
        mDiskCache.remove(bitmapRequest);
    }

    public boolean isDiskExist(String md5) {
        return mDiskCache.isExist(md5);
    }
}
